import axios from 'axios'
import {ElMessage} from 'element-plus'
import mock from '../../mock/index'

const service = axios.create({
  baseURL: import.meta.env.BASE_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
  adapter: config => {
    const result = mock(config)
    if (result != null)
      return result
    return service.request(config)
  }
})

service.interceptors.request.use(
  config => {
    config.headers.Authorization = sessionStorage.getItem('token') || ''
    // if (config.method.toLowerCase() == 'get') {
    //   config.params = config.data
    //   config.data = null
    // }
    // console.log('request', config)
    return config
  },
  error
)

service.interceptors.response.use(
  response => {
    // console.log(response)
    if (response.status !== 200)
      return error(new Error('请求失败'))
    const result = response.data
    // if (result instanceof Blob) {
    //   return result
    // }
    if (!result.success)
      return error(new Error(result.message))
    return result
  },
  error
)

function error(error) {
  console.error(error)
  let message = error.message || '请求异常'
  if (error.name)
    message = message.includes('timeout') ? '请求超时' : '请求异常'
  ElMessage.error(message)
  return Promise.resolve({
    success: false,
    message,
  })
}

/**
 axios(config)
 axios(url[, config])
 axios.request(config)
 axios.get(url[, config])
 axios.delete(url[, config])
 axios.head(url[, config])
 axios.post(url[, data[, config]])
 axios.put(url[, data[, config]])
 axios.patch(url[, data[, config]])
 */
export default service
